<template>
	<view>
		<uni-nav-bar @clickLeft="$tab.back()" fixed="true" color="#fff" left-icon="left" backgroundColor="#FA554E"
			title="发布商品" statusBar="true" :border="false" />

		<view class="px-20 py-20">
			<u--form labelPosition="left" :model="form" :rules="rules" ref="form" :labelWidth="120">
				<u-form-item label="商品名称" prop="name" borderBottom required>
					<u--input v-model="form.name" border="none" placeholder="请输入商品名称"></u--input>
				</u-form-item>
				<u-form-item label="商品现价" prop="price" borderBottom required>
					<u--input v-model="form.price" border="none" placeholder="请输入商品现价" type="number"></u--input>
				</u-form-item>
				<u-form-item label="让利比例" prop="discountRate" borderBottom required>
					<u--input v-model="form.discountRate" border="none" placeholder="请输入让利比例(1-100)"
						type="number"></u--input>
				</u-form-item>
				<u-form-item label="商品分类" prop="type" borderBottom @click="typeListShow = true;hideKeyboard()">
					<u--input :value="typeName" disabled disabledColor="#ffffff" placeholder="请选择规格" border="none">
					</u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="商品规格" prop="brand" borderBottom required @click="addSpu();hideKeyboard()">
					<u--input :value="commodityModels" disabled disabledColor="#ffffff" placeholder="请选择规格"
						border="none">
					</u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="商品封面" prop="cover" borderBottom required :label-width="100">
					<div class="" @click="$tab.nav(`/pages/mine/store/editPic?image=${globalConfig.imagePrefix + form.cover}`)">
						<view class="cover" v-if="!form.cover">
							<u-icon name="camera-fill" color="#D3D4D6" size="52rpx"></u-icon>
						</view>
						<image :src="globalConfig.imagePrefix + form.cover" class="cover" mode="" v-else></image>
					</div>
				</u-form-item>
				<u-form-item label="商品banner" prop="prodIcons" borderBottom required :label-width="100">
					<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="banner"
						:multiple="true" :maxCount="3"></u-upload>
				</u-form-item>
				<view class="">
					<view class="flex align-c flex_j_b py-28">
						<view class="color-333" style="font-size:30rpx;">
							<text style="color: #f56c6c;">*</text>商品详情：
						</view>
					</view>
					<jinEdit placeholder="请输入内容" :uploadFileUrl="uploadFileUrl" :header="header" height="200"
						v-model="form.detail"></jinEdit>
				</view>
			</u--form>
		</view>

		<!-- S 所属分类列表  -->
		<u-picker @cancel="typeListShow=false" @confirm="selectConfirm" :show="typeListShow" :columns="typeList"
			keyName="name"></u-picker>
		<!-- E 所属分类列表 -->

		<view class="flex justify-around">
			<u-button text="发布商品" style="background-color: #FA554E;color: #fff;" @click="shappingAdd"></u-button>
		</view>

		<view class="" style="width: 100%;height: 100rpx;"></view>
	</view>
</template>

<script>
	import jinEdit from '@/components/jin-edit/jin-edit.vue';
	import {
		getToken
	} from '@/utils/auth'
	export default {
		components: {
			jinEdit
		},
		data() {
			return {
				stutasHeight: uni.getSystemInfoSync().statusBarHeight + 44,
				form: {
					type: "", //商品所属分类
					name: "", //商品名称
					price: null, //商品现价
					icons: "", //商品轮播图
					detail: "", //商品详情
					mallSkus: null, //商品规格
					storeId: "", //商铺id
					cover: "", //商品封面
					columnType: 3,
					discountRate: ""
				},
				rules: {
					name: {
						type: 'string',
						required: true,
						message: '请填写商品名称',
						trigger: ['blur', 'change']
					},
					price: {
						type: 'number',
						required: true,
						message: '请填写商品现价',
						trigger: ['blur', 'change']
					},
					icons: {
						type: 'string',
						required: true,
						message: '请上传商品轮播图',
						trigger: ['change']
					}
				},
				navArr: [], //导航分类数组
				uploadFileUrl: getApp().globalData.config.baseUrl + '/common/upload',
				header: {
					'Authorization': 'Bearer ' + getToken()
				},
				fileList: [], //商品banner
				typeList: [], //所属分类列表
				typeListShow: false, //商品所属分类弹窗
				typeName: null, //商品所属分类名字
				commodityModels: '', //判断商品规格显示的值
				html: "", //初始化商品详情
				globalConfig: getApp().globalData.config
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.form.setRules(this.rules)
		},
		onLoad(e) {
			// 获取初始数据
			this.getData(e.product)
		},
		methods: {
			// 获取初始数据
			async getData(id) {
				const response = await this.$Api.common.typeChildrenAll({
					code: "classification"
				})
				console.log(response, '商品分类');
				this.typeList.push(response.data)

				const shopId = await this.$Api.store.appgetstores()
				console.log(shopId, 'shopId')
				this.form.storeId = shopId.data.id

				// 有id则获取详情
				if (id) {
					const {
						data
					} = await this.$Api.index.commodityDetail(id)

					// 商品分类处理
					this.typeList[0].forEach(item => {
						if (item.id == data.type) {
							this.typeName = item.name
						}
					})

					this.fileList = data.icons.split(',').map(item => {
						return {
							url: this.globalConfig.imagePrefix + item
						}
					})

					// 商品规格图片处理
					data.mallSkus.forEach(item => {
						item.skuIcon = [this.globalConfig.imagePrefix + item.icons]
					})

					// 规格
					this.commodityModels = '已添加'
					this.form = data

					this.$nextTick(() => {
						// 富文本处理
						this.html = data.detail
					})
				}
			},
			/* 所属分类选择确认按钮 */
			selectConfirm(e) {
				this.typeName = e.value[0].name
				this.form.type = e.value[0].id
				this.typeListShow = false
			},
			updateCover(e){
				this.form.cover = e
			},
			hideKeyboard() {
				uni.hideKeyboard()
			},
			addSpu() {
				let that = this
				uni.navigateTo({
					url: `/pages/mine/store/addSpu`
				})
			},
			/* 商品添加 */
			async shappingAdd() {
				if (this.form.mallSkus == null && !this.form.id) {
					this.$modal.msg('请添加商品规格')
					return
				}
				if (this.form.detail == "") {
					this.$modal.msg('请添加商品详情')
					return
				}

				if (this.discountRate > 100 || this.discountRate < 1) {
					this.$modal.msg('让利比例输入范围为1-100')
					return
				}

				this.form.mallSkus && this.form.mallSkus.forEach(item => {
					item.icons = item.skuIcon[0].replace(this.globalConfig.imagePrefix, "")
				})

				this.$refs.form.validate().then(validate => {


					if (this.form.id) {
						this.$Api.store.amendCommodity(this.form).then(res => {
							console.log('商品基本属性修改:', res)
							this.$modal.msg('修改成功')
							this.$tab.back(1500)
						})
					} else {
						this.$Api.store.addProductsSpu(this.form).then(res => {
							this.$modal.msg('添加成功')
							this.$tab.back(1500)
						})
					}
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},

			// 设置mallSkus值
			setmallSkus(mallSkus) {
				this.form.mallSkus = mallSkus
				this.commodityModels = '已添加'
			},
			// 删除图片
			deletePic(event) {
				switch (event.name) {
					case "banner":
						this.fileList.splice(event.index, 1)
						this.form.inDoorOne = ''
						this.fileList.forEach((item, index) => {
							if (index == 0) {
								this.form.icons = item.fileName
							} else {
								this.form.icons = this.form.icons + ',' + item.fileName
							}
						})
						break
				}
			},
			// 新增图片
			async afterRead(event) {
				const res = await this.$Api.common.uploadFile((event.file[0].thumb))
				switch (event.name) {

					case "banner":
						this.fileList.push({
							url: res.url,
							fileName: res.fileName
						})
						this.form.inDoorOne = ''
						this.fileList.forEach((item, index) => {
							if (index == 0) {
								this.form.icons = item.fileName
							} else {
								this.form.icons = this.form.icons + ',' + item.fileName
							}
						})
						break
				}
			}
		}
	}
</script>
<style>
	page {
		background-color: #fff;
	}
</style>
<style lang="scss" scoped>
	/deep/ .u-radio {
		margin-right: 108rpx;
	}

	/deep/ .uni-input-wrapper {
		text-align: right;
	}

	/deep/ .u-form-item__body__right__message {
		text-align: right;
	}

	.bioati {
		font-size: 28rpx;
		font-weight: 400;
		color: #333333;
		line-height: 32rpx;
	}

	.text01 {
		font-size: 28rpx;
		font-weight: 400;
		color: #999999;
		line-height: 32rpx;
	}

	.box-1 {
		padding: 16rpx 0rpx;
		border-bottom: 2rpx solid #EAEAEA;
	}

	.cover {
		width: 150rpx;
		height: 150rpx;
		display: flex;
		align-items: center;
		justify-content: space-around;
		background-color: #F4F5F7;
	}
</style>